import axios from "axios";
import Vue from "vue"
import Router from 'vue-router'


Vue.use(Router);

const routes = [
    {

        path: '/app',
        component: () => import('../views/app'),

    },
    {
        path: '/AllProduct',
        component: () => import('../views/AllProduct')
    },
    {
        path: '/',
        redirect: 'login'
    },
    {
        path: '/sales',
        component: () => import('../views/sales')
    },
    {
        path: '/purchase',
        component: () => import('../views/purchase')
    },
    {
        //登录页
        path: '/login',
        component: () => import('../components/Login')
    },
    {
        //注册页
        path:'/Register',
        component:()=>import('../components/Regist')
    },
    {
        //测试页
        path: '/test3',
        component: () => import('../views/test3')
    }

]

const router = new Router({

    mode: "history",
    routes
})

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
router.beforeEach((to, from, next) => {
    if (to.path.startsWith('/login')) {  //如果是登录页
        //删除本地存储数据
        // window.localStorage.removeItem('token');
        //vuex
        sessionStorage.removeItem('user');
        sessionStorage.removeItem('token');
        next();
    }else if(to.path.startsWith('/Register')){   //如果是注册页
         //删除本地存储数据
        //  window.localStorage.removeItem('token');
         //vuex
         sessionStorage.removeItem('user');
         sessionStorage.removeItem('token');
        next();
    }
     else {
        // let admin = window.localStorage.getItem('token')
        let admin = sessionStorage.getItem('token')
        if (admin==null) {  //如果对象不存在
            alert('请先登录账号！！！')
            next({ path: '/login' });
        } else {
            //校验token的合法性
            console.log('校验token的合法性')
            console.log(admin)
            axios({
                url: ' http://localhost:8088/checkToken',
                method: 'get',
                headers: {
                    Authorization: admin
                }
            }).then((response) => {
                if (!response.data) {
                    console.log('校验失败')
                    next({ path: '/login' })
                }
            })
            next();
        }
    }
})

export default router


